package hedron.db.model;

import hedron.Application;
import hedron.db.DBManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.logging.Level;

public abstract class AbstractModel {
	final String EMPTY_STR = "";

	public abstract long getID();

	public abstract String getIDName();

	public abstract String getTableName();

	public abstract boolean isValid();

	public abstract boolean load(ResultSet rs);

	abstract boolean store(Connection conn);

	final DBManager db;

	public AbstractModel() {
		db = Application.DB;
	}

	public boolean load(Connection conn) {
		StringBuilder sql = new StringBuilder();
		sql.append("select * from ");
		sql.append(getTableName());
		sql.append(" where ").append(getIDName()).append(" = ").append(getID());
		ResultSet rs = db.query(conn, sql.toString());
		if (rs != null) {
			if (db.next(rs)) {
				return load(rs);
			}
			db.close(rs);
		}
		return false;
	}

	public final boolean load() {
		boolean result = false;
		if (getID() > 0) {
			Connection conn = db.getConnection();
			if (conn != null) {
				result = load(conn);
				db.closeConnection(conn);
			}
		}
		return result;
	}

	public final boolean delete() {
		boolean result = false;
		if (getID() > 0) {
			Connection conn = db.getConnection();
			if (conn != null) {
				result = delete(conn);
				db.closeConnection(conn);
			}
		}
		return result;
	}

	public boolean delete(Connection conn) {
		StringBuilder sql = new StringBuilder();
		sql.append("delete from ");
		sql.append(getTableName());
		sql.append(" where ").append(getIDName()).append(" = ").append(getID());
		return db.ddlQuery(conn, sql.toString());
	}

	public final boolean store() {
		boolean result = false;
		if (isValid()) {
			Connection conn = db.getConnection();
			if (conn != null) {
				result = store(conn);
				db.closeConnection(conn);
			}
		} else {
			Application.log.log(Level.SEVERE, this.getClass().getName() + ": model is invalid");
		}
		return result;
	}

	boolean isNotEmpty(String str) {
		return str != null && str.length() > 0;
	}
}
